﻿using Newtonsoft.Json;
using SmartPlant.Model;
using SmartPlant.Model.Biz;
using SmartPlant.Model.DbContext;
using SmartPlant.Model.DbContext.Biz;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using SmartPlant.WinCore.Config;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace SmartPlant.Services
{
    public class DynamicDataApiService : DynamicColumnService, IDynamicDataApi
    {
        #region IndexTable
        ///// <summary>
        ///// 从JSON文本中加载索引表数据。（本地文件）
        ///// </summary>
        ///// <param name="jsonStr"></param>
        ///// <returns></returns>
        //public async Task<dynamic> LoadIndexTableFromJsonAsync(string jsonStr)
        //{
        //    var propertyInfos = await InitIndexTablePropertyInfosAsync(GlobalObject.CurrentProject.ProjId.ToString());
        //    var objType = DynamicClassHelper.CreateDynamicType(GlobalObject.IndexTableEntityName, propertyInfos);
        //    if (objType == null)
        //    {
        //        throw new System.ArgumentNullException(nameof(objType), $"未找到对应的{nameof(objType)}实体信息!!!");
        //    };
        //    var listType = typeof(ObservableCollection<>);
        //    var constructedListType = listType.MakeGenericType(objType);
        //    var data = JsonConvert.DeserializeObject(jsonStr, constructedListType);
        //    return data;
        //}

        /// <summary>
        /// 保存索引表数据。
        /// </summary>
        /// <param name="proId">工程ID。</param>
        /// <param name="submitObj"></param>
        /// <returns></returns>
        public async Task<bool> SaveIndexTableAsync(string proId, EDESubmitObj submitObj)
        {
            string uri = $"/api/Project/{proId}/EDE-api/save-index-default/false";
            var r = await PostBodyAsync<bool?, EDESubmitObj>(uri, submitObj);
            return r.succeeded;
        }

        public async Task<PageResult<dynamic>> GetIndexTableDynamicsAsync(string proId, List<ViewQueryItemAttr> ColsChecked, string unitids, int pagenum, int pagesize)
        {
            string uri = $"/api/Project/{proId}/EDE-api/index-default/{pagenum}/{pagesize}/{unitids}";
            var propertyInfos = await InitIndexTablePropertyInfosAsync(proId);
            var objType = DynamicClassHelper.CreateDynamicType(GlobalObject.IndexTableEntityName, propertyInfos);
            if (objType == null) return null;

            var listType = typeof(ObservableCollection<>);
            var constructedListType = listType.MakeGenericType(objType);//转为 ObservableCollection<IndexTableEntity>

            var result = await GetDynamicObjAsync(constructedListType, uri); //给的就是具体的值，而非ID，比如instrument location
            var tmpData = (IList)result.Data;
            foreach (var item in tmpData)
            {
                var editObj = item as DynamicEntity; //在 MakeCode 里，写的xxx.cs里，继承了 DynamicEntity
                if (editObj != null)
                {
                    editObj.IsModify = false;
                }
            }
            result.Data = tmpData;
            return result;
        }
        /// <summary>
        /// 查询EDE里，仪表索引,默认的列信息
        /// </summary>
        /// <param name="proId"></param>
        /// <returns></returns>
        public async Task<List<ViewQueryItemAttr>> GetIndexTableDataColumnsAsync(string proId)
        {
            string uri = $"/api/Project/{proId}/EDE-api/index-default-columns";//item id = 1071
            var res = await GetAsync<List<ViewQueryItemAttr>>(uri);//会很慢
            return res.data;
        }

        public async Task<List<DynamicPropertyInfo>> InitIndexTablePropertyInfosAsync(string proId)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            var cacheObj = GlobalObject.IndexTablePropertyInfos;
            if (cacheObj != null) return cacheObj;//避免重复下面的http请求
            GlobalObject.EDE_Index_AllColumns = await GetIndexTableDataColumnsAsync(proId);

            var propertyInfos = ConvertColumns(GlobalObject.EDE_Index_AllColumns);
            var config = ConfigHelper.ReadConfig();
            var savedInfoSegment = config.IndexViewColDef;
            if (savedInfoSegment != null)
            {

                if (savedInfoSegment.Count > 0)
                {
                    var savedInfo = savedInfoSegment[0];
                    var colDef = savedInfo.Split("|").ToList(); //只会来一次
                    List<string> colNames = new List<string>();
                    int seq = 1;
                    foreach (var col in colDef)
                    {
                        var nameAndOrder = col.Split("@");
                        if (nameAndOrder.Length > 1)
                        {
                            var prop = propertyInfos.FirstOrDefault(x => x.PropertyName == nameAndOrder[0]);
                            if (prop != null)
                            {
                                prop.DisplayName = nameAndOrder[1];
                                prop.IsVisible = true;
                                prop.Order = seq;
                                seq++;
                            }
                            colNames.Add(nameAndOrder[0]);
                        }
                    }


                    foreach (var dynamicProperty in propertyInfos.Where(x => !colNames.Contains(x.PropertyName)))
                    {
                        dynamicProperty.IsVisible = false;
                        dynamicProperty.Order = 0;
                    }
                }

            }

            GlobalObject.IndexTablePropertyInfos = propertyInfos;
            stopwatch.Stop();
            Console.WriteLine("InitIndexTablePropertyInfosAsync: " + stopwatch.ElapsedMilliseconds);
            return propertyInfos;
        }

        public async Task<bool> InitIndexTablePropertyDropDownListAsync(string ProjId, List<DynamicPropertyInfo> propertyInfos)
        {
            Stopwatch x = Stopwatch.StartNew();
            var codelistServer = new CodeListService();
            CodeListService.DropDownListsAll.Clear();
            //Parallel.ForEach(propertyInfos.Where(x => x.IsDropDown == true).ToList(), async (p) =>
            //{
            //    var list = await codelistServer.GetDropDownListAsync(ProjId, p.ItemAttributionId);
            //    GlobalObject.PropertyDropDownList.Add(ProjId + "_" + p.ItemAttributionId, list);
            //});


            //ATTRIBUTE_DATATYPE
            var downlist = propertyInfos.Where(x => x.IsDropDown == true).Select(x => x.ItemAttributionId.ToString()).ToList();
            var downlist2 = propertyInfos.Where(x => x.IsDropDown == true).Select(x => x.ATTRIBUTE_DATATYPE.ToString()).ToList();
            await codelistServer.GetDropDownListsByAttrAsync(ProjId, downlist);
            x.Stop();
            Console.WriteLine("InitIndexTablePropertyDropDownListAsync: " + x.ElapsedMilliseconds);
            return true;
        }
        #endregion

        #region DrawingDoc
        /// <summary>
        /// 获取图形文档动态类属性信息。
        /// </summary>
        /// <param name="proId">工程ID。</param>
        /// <returns></returns>
        public async Task<List<DynamicPropertyInfo>> InitDrawingDocPropertyInfosAsync(string proId)
        {
            var cacheObj = GlobalObject.DrawingDocPropertyInfos;
            if (cacheObj != null) return cacheObj;
            var viewQueryItems = await GetDrawingDocDataColumnsAsync(proId);
            var propertyInfos = ConvertColumns(viewQueryItems);
            GlobalObject.DrawingDocPropertyInfos = propertyInfos;
            return propertyInfos;
        }
        /// <summary>
        /// 分页获取图形文档动态数据。
        /// </summary>
        /// <param name="pagenum"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public async Task<PageResult<List<Drawing>>> GetDrawingDocDynamicsAsync(string proId, int pagenum, int pagesize)
        {
            string uri = $"/api/Project/{proId}/EDE-api/drawing-default/{GlobalObject.CurrentUnit.PlantId}/{pagenum}/{pagesize}";
            var propertyInfos = await InitDrawingDocPropertyInfosAsync(proId);

            var result = await GetAsync<PageResult<List<Drawing>>>(uri);
            return result.data;
        }

        /// <summary>
        /// 获取图形文档动态数据对应的数据列。
        /// </summary>
        /// <returns></returns>
        public async Task<List<ViewQueryItemAttr>> GetDrawingDocDataColumnsAsync(string proId)
        {
            string uri = $"/api/Project/{proId}/EDE-api/drawing-default-columns";
            var res = await GetAsync<List<ViewQueryItemAttr>>(uri);
            return res.data;
        }


        #endregion
    }
}
